package com.e.library.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.e.library.R;
import com.e.library.dialog.ELoading;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EResponse;
import com.e.library.http.EResponseListener;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.Utils;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityHelper;

/**
 * 支持滑动退出
 * 支持沉浸式状态栏
 * 支持ButterKnife注解绑定
 * Created by lxy on 2016/5/9.
 */
public abstract class EActivity extends AppCompatActivity{

    protected ELoading mLoading;
    protected Unbinder mUnbinder;
    protected SwipeBackActivityHelper mHelper;
    protected SwipeBackLayout mSwipeBackLayout;
    protected SystemBarTintManager mTintManager;

    protected abstract int layout();
    protected abstract void onActivityCreated(Bundle state);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        } else {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        mTintManager = new SystemBarTintManager(this);
        mTintManager.setStatusBarTintEnabled(true);
        mTintManager.setStatusBarTintResource(R.color.e_purple);

        initSwipBackLayout();
        initContentView();
        mUnbinder = ButterKnife.bind(this);
        onActivityCreated(savedInstanceState);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    protected void statusBar(int res){
        if (mTintManager != null){
            mTintManager.setStatusBarTintResource(res);
        }
    }

    @TargetApi(19)
    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected void initSwipBackLayout() {
        mHelper = new SwipeBackActivityHelper(this);
        mHelper.onActivityCreate();
        mSwipeBackLayout = mHelper.getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
    }

    protected void initContentView() {
        View view = LayoutInflater.from(this).inflate(layout(), null);
        //view.setBackgroundColor(getResources().getColor(R.color.e_background));
        setContentView(view);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mHelper.onPostCreate();
    }

    @Override
    public View findViewById(int id) {
        View v = super.findViewById(id);
        if (v == null && mHelper != null)
            return mHelper.findViewById(id);
        return v;
    }

    public SwipeBackLayout getSwipeBackLayout() {
        return mSwipeBackLayout;
    }

    public void setSwipeBackEnable(boolean enable) {
        mSwipeBackLayout.setEnableGesture(enable);
    }

    protected void disableSwipeBack() {
        setSwipeBackEnable(false);
    }

    public void setSwipeBackEdge(int edge) {
        mSwipeBackLayout.setEdgeTrackingEnabled(edge);
    }

    public void scrollToFinishActivity() {
        Utils.convertActivityToTranslucent(this);
        mSwipeBackLayout.scrollToFinishActivity();
    }

    public void toActivityForResult(Class<?> clazz, Bundle extras, int requestCode) {
        Intent mIntent = new Intent(this, clazz);
        if (extras != null) {
            mIntent.putExtras(extras);
        }
        startActivityForResult(mIntent, requestCode);
    }

    public void toActivityForResult(Class<?> clazz, int requestCode) {
        toActivityForResult(clazz,null,requestCode);
    }

    public void toActivity(Class<?> clazz, Bundle extras) {
        Intent mIntent = new Intent(this, clazz);
        if (extras != null) {
            mIntent.putExtras(extras);
        }
        startActivity(mIntent);
    }

    public void toActivity(Class<?> clazz) {
        toActivity(clazz, null);
    }

    public void toActivity(String action) {
        toActivity(action, null);
    }

    public void toActivity(Intent intent) {
        if (intent == null) {
            return;
        }
        startActivity(intent);
    }

    public void toActivity(String action, Bundle extras) {
        Intent mIntent = new Intent(action);
        if (extras != null) {
            mIntent.putExtras(extras);
        }
        startActivity(mIntent);
    }

    public void defaultFinish() {
        hideKeybord();
        dismiss();
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public void onBackPressed() {
        defaultFinish();
    }

    public void longToast(int resid) {
        Toast.makeText(this, resid, Toast.LENGTH_LONG).show();
    }

    public void longToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

    public void toast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    public void toast(int resid) {
        Toast.makeText(this, resid, Toast.LENGTH_SHORT).show();
    }

    public void hideKeybord() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView()
                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void loading(){
        loading("");
    }

    public void loading(int text){
        String s = getString(text);
        loading(s);
    }

    public void loading(String text){
        if (mLoading == null){
            mLoading = new ELoading(this);
        }
        if (!mLoading.isShowing()){
            mLoading.showLoading(text);
        }
    }

    public void dismiss(){
        if (isFinishing()){
            mLoading = null;
            return;
        }
        if (mLoading !=null && mLoading.isShowing()){
            mLoading.dismiss();
        }
    }

    public void dismiss(String msg){
        dismiss();
        toast(msg);
    }

    public void dismiss(int resid){
        dismiss();
        toast(resid);
    }

    @Override
    protected void onDestroy() {
        dismiss();
        mLoading = null;
        if (mUnbinder !=null){
            mUnbinder.unbind();
        }
        super.onDestroy();
    }

    public EApi api(){
        return EClient.with(this).api();
    }
    public void post(String url, Map<String, String> params, final EResponseListener listener) {
        Observable<EResponse> observable = api().post(url,params);
        subscribe(observable,listener);
    }

    public void get(String url, final EResponseListener listener) {
        Observable<EResponse> observable = api().get(url);
        subscribe(observable,listener);
    }

    public void get(String url, Map<String, String> params, final EResponseListener listener) {
        Observable<EResponse> observable =api().get(url,params);
        subscribe(observable,listener);
    }

    public void subscribe(Observable<EResponse> observable,final EResponseListener listener) {
        subscribe(observable,listener,true);
    }

    /**
     * @param listener
     * @param showLoading 是否显示loading
     */
    public void subscribe(final Observable<EResponse> observable, final EResponseListener listener, final boolean showLoading) {
//        EResponseSubscriber subscriber = new EResponseSubscriber(){
////            @Override
////            public void onStart() {
////                if (loading){
////                    loading();
////                }
////            }
//
//            @Override
//            public void onSubscribe(Subscription s) {
//
//            }
//
//            @Override
//            public void onComplete() {
//                dismiss();
//            }
//
//            @Override
//            public void onFail(String msg) {
//                super.onFail(msg);
//                dismiss(msg);
//            }
//        }.callback(listener);
//        observable.retryWhen(new RetryLogin(this))
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);


    }


}
